package com.quark.framework.configuration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONSerializer;

import com.quark.framework.base.QuarkEnvironment;
import com.quark.framework.i18n.QuarkI18nConfiguration;
import com.quark.framework.utility.QuarkLog;
import com.quark.framework.utility.QuarkUtilFileReader;

public class QuarkConfigManager {
	
	private Map<String, QuarkConfigBase> mapping = new HashMap<String, QuarkConfigBase>();
	private static QuarkConfigManager inst = new QuarkConfigManager();
	private List<Class<? extends QuarkConfigBase>> configList = new ArrayList<Class<? extends QuarkConfigBase>>();
	private QuarkConfigManager()
	{

	}
	
	public static QuarkConfigManager getInstance()
	{
		return inst;
	}
	
	public QuarkConfigBase loadConfiguration(String configName)
	{
		try
		{
			//TODO:set path
			
			String path = QuarkEnvironment.getInstance().getWorkingPath() + "config\\";
			QuarkConfigBase config = QuarkConfigBase.class.cast(Class.forName(configName).newInstance());
			
			QuarkLog.logMessage("Config:" + path + config.getClass().getSimpleName() + ".txt");
			config.loadFromJSON(path + config.getClass().getSimpleName() + ".txt");
			mapping.put(config.getClass().getSimpleName(), config);
			return config;
		}catch(Exception e)
		{
			QuarkLog.log(e);
			return null;
		}
	}
	
	public QuarkConfigBase getConfiguration(Class<? extends QuarkConfigBase> configClass)
	{
		QuarkConfigBase config = mapping.get(configClass.getSimpleName());
		if(config == null)
		{
			QuarkLog.logError("no such configuration: " + configClass.getSimpleName());
		}
		return config;
	}
	
	public void registerConfigRequire(Class<? extends QuarkConfigBase> configClass)
	{
		configList.add(configClass);
	}
	
	public boolean init()
	{
		return loadAllConfiguration();
	}
	
	public boolean loadAllConfiguration()
	{
		String path = QuarkEnvironment.getInstance().getWorkingPath() + "config\\";
		String configList = QuarkUtilFileReader.readAllString(path + "QuarkConfigList.txt");
		QuarkLog.logMessage(path + "QuarkConfigList.txt");
		JSONArray array = JSONArray.fromObject(configList);
		for(int i = 0; i < array.size(); i++)
		{
			mapping.put(array.get(i).toString(), loadConfiguration(array.get(i).toString()));
		}
		return true;		
	}
	public boolean uninit()
	{
		return true;
	}
}
